package ms.jasim.framework;

public class JasimAppContext implements IJasimAppContext {

	private String name;
	private IJasimAppContext parent;
	private IServiceProvider services;
	
	public static IJasimAppContext createRootContext() throws Exception {
		IJasimAppContext context = new ms.jasim.framework.JasimAppContext(null, "$root");
		return context;
	}
	
	public JasimAppContext(IJasimAppContext parentContext, String name) {
		this.name = name;
		parent = parentContext;
		services = new JasimServiceProvider();
	}
	
	@Override
	public String Name() {
		return name;
	}

	@Override
	public IJasimAppContext ParentContext() {
		return parent;
	}

	@Override
	public IJasimAppContext Root() {
		return parent != null ? parent : parent.Root();
	}

	@Override
	public IJasimAppContext createChildContext(String name) {
		return new JasimAppContext(this, name);
	}

	@Override
	public void addService(Object svcInstance) {
		services.addService(svcInstance);
	}

	@Override
	public <T> T getService(Class<T> svcContract) {
		T result = services.getService(svcContract);
		return result != null ? result : parent != null ? parent.getService(svcContract) : null;
	}


	@Override
	public void removeService(Object service) {
		services.removeService(service);
	}

}
